﻿using Microsoft.AspNetCore.Mvc;
using Entity;
using IService;
using System.Net;
using Dapper;
using System.Data;

namespace XingWeiDaWMSProject.Controllers
{
    public class PurchaseOrderController : Controller
    {
        private readonly IProductInformationService _productInformation;
        private readonly IPurchaseOrderService _purchaseOrderService;
        private readonly IDbConnection _dbConnection;

        public PurchaseOrderController(IProductInformationService productInformation, IPurchaseOrderService purchaseOrderService, IDbConnection dbConnection)
        {
            _productInformation = productInformation;
            _purchaseOrderService = purchaseOrderService;
            _dbConnection = dbConnection;
        }

        /// <summary>
        /// 订单管理页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        /// <summary>
        /// 订单管理添加页面
        /// </summary>
        /// <returns></returns>
        public IActionResult AddPage()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        /// <summary>
        /// 订单管理详情页面
        /// </summary>
        /// <returns></returns>
        public IActionResult DetailsPage()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetByCode(
            int currentPage = 1, 
            int pageSize = 10, 
            string? code = null, 
            string? Unit = null)
        {
            try
            {
                // 1. 调用Service层获取分页数据
                var pagedData = await _productInformation.GetByCodeAsync(pageSize, currentPage, code, Unit);

                // 2. 封装统一响应格式（与前端期望的{success, message, data, total}匹配）
                return Json(new
                {
                    success = true,
                    message = "查询成功",
                    data = pagedData.items, // 分页数据列表
                    total = pagedData.total  // 总数据条数（用于分页控件）
                });
            }
            catch (Exception ex)
            {
                // 3. 异常处理
                return Json(new
                {
                    success = false,
                    message = $"查询失败：{ex.Message}",
                    data = new List<ProductInformationFind>(), // 空列表避免前端报错
                    total = 0
                });
            }
        }
        

        /// <summary>
        /// 新增进货订单（含明细）
        /// </summary>
        [HttpPost("api/PurchaseOrder/Add")]
        public async Task<IActionResult> AddPurchaseOrder([FromBody] PurchaseOrderRequest request)
        {
            try
            {
                // 1. 构造主表实体（保持不变）
                var order = new PurchaseOrderEntity
                {
                    purchase_order_no = request.purchase_order_no,
                    supplier_id = request.supplier_id,
                    suppliers_id = request.suppliers_id,
                    purchase_date = request.purchase_date,
                    document_status = "2",
                    contact_person = request.contact_person,
                    contact_information = request.contact_information,
                    purchaser = request.purchaser,
                    reviewer = null,
                    review_time = DateTime.Now,
                    organizations_id = request.organizations_id,
                    note = request.note,
                    create_by = "admin",
                    create_time = DateTime.Now,
                    is_delete = "0"
                };

                // 2. 构造明细列表（新增：赋值Product_ID）
                var details = new List<WmsOrderDetails>();
                foreach (var detailReq in request.details)
                {
                    details.Add(new WmsOrderDetails
                    {
                        Product_ID = detailReq.Product_ID, // 新增：赋值货品ID
                        purchase_unit_price = detailReq.purchase_unit_price,
                        prod_num = detailReq.prod_num,
                        note = detailReq.note
                    });
                }

                // 3. 调用服务方法（保持不变）
                bool isSuccess = await _purchaseOrderService.AddPurchaseOrderWithDetailsAsync(order, details);

                if (isSuccess)
                {
                    return Json(new { success = true, message = "进货订单及明细新增成功" });
                }
                else
                {
                    return Json(new { success = false, message = "明细插入失败，请重试" });
                }
            }
            catch (ArgumentException ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"服务器错误：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取进货订单列表（分页+筛选）
        /// </summary>
        [HttpGet("api/PurchaseOrder/GetList")]
        public async Task<IActionResult> GetPurchaseOrders(
            int currentPage = 1,
            int pageSize = 10,
            string? purchaseOrderNo = null, // 进货单号筛选
            string? status = null,          // 状态筛选
            DateTime? startDate = null,     // 开始日期
            DateTime? endDate = null)       // 结束日期
        {
            try
            {
                // 调用服务层获取分页数据（需在IPurchaseOrderService和实现类中实现该方法）
                var pagedData = await _purchaseOrderService.GetPurchaseOrdersAsync(
                    currentPage, pageSize, purchaseOrderNo, status, startDate, endDate);

                return Json(new
                {
                    success = true,
                    data = pagedData.items, // 此时data是PurchaseOrderDTO列表
                    total = pagedData.total
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    message = $"查询失败：{ex.Message}",
                    data = new List<PurchaseOrderEntity>(),
                    total = 0
                });
            }
        }


        /// <summary>
        /// 根据进货单号获取订单详情（含明细）
        /// </summary>
        [HttpGet("api/PurchaseOrder/GetPurchaseOrderDetail")]
        public async Task<IActionResult> GetPurchaseOrderDetail(string orderNo)
        {
            try
            {
                var (main, details) = await _purchaseOrderService.GetPurchaseOrderDetailAsync(orderNo);
                return Json(new { success = true, data = new { main, details } });
            }
            catch (ArgumentException ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
            catch (KeyNotFoundException ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "系统异常，请稍后重试" });
            }
        }


        public async Task<IActionResult> UpdateReview(string code, string status, string txt =null)
        {
            if (code == null)
            {
                return Json(new
                {
                    success = false,
                    message = "订单编号为空"
                });
            }
            await _purchaseOrderService.UpdateReview(code,txt,status);

            return Json(new
            {
                success = true,
                message = "审核成功"
            });
        }

        [HttpPost("api/PurchaseOrder/BatchUpdateReview")]
        public async Task<IActionResult> BatchUpdateReview([FromBody] BatchReviewRequest request)
        {
            try
            {
                if (request.OrderNos == null || request.OrderNos.Count == 0)
                {
                    return Json(new { success = false, message = "请选择要审核的订单" });
                }

                // 从Session获取当前登录人
                string reviewer = HttpContext.Session.GetString("LoginUserName");
                if (string.IsNullOrEmpty(reviewer))
                {
                    return Json(new { success = false, message = "未获取到登录人信息，请重新登录" });
                }

                await _purchaseOrderService.BatchUpdateReview(request.OrderNos, request.Status, request.Opinion, reviewer);
                return Json(new { success = true, message = "批量审核成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"审核失败：{ex.Message}" });
            }
        }


        /// <summary>
        /// 查询可关联的进货单（未入库/部分入库）
        /// </summary>
        [HttpGet("api/PurchaseOrder/GetRelatedOrders")]
        public async Task<IActionResult> GetRelatedOrders(
            string inboundType,
            List<string> status,
            int? supplierId = null,
            string? purchaseOrderNo = null,
            string? purchaser = null,
            string? department = null,
            string? date = null,
            int page = 1,
            int size = 10)
        {
            try
            {
                var result = await _purchaseOrderService.GetRelatedOrdersAsync(
                    inboundType, status, supplierId, purchaseOrderNo, purchaser, department, date, page, size);
                return Ok(new { success = true, data = result.items, total = result.total });
            }
            catch (Exception ex)
            {
                return Ok(new { success = false, message = ex.Message, data = new object[0], total = 0 });
            }
        }
        

        /// <summary>
        /// 获取进货订单列表（分页+筛选）
        /// </summary>
        [HttpGet("api/PurchaseOrder/GetListStorage")]
        public async Task<IActionResult> GetListStorage(string id)       // 结束日期
        {
            try
            {
                string sql = "select * from wms_basic_storage_location WHERE warehouse_id = " + id;
                List< StorageLocationEntity > list = (await _dbConnection.QueryAsync<StorageLocationEntity>(sql)).ToList();
                return Json(new
                {
                    success = true,
                    data = list,
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    message = $"查询失败：{ex.Message}",
                    data = new List<PurchaseOrderEntity>(),
                    total = 0
                });
            }
        }


    }
}